package rus.sq.osTicket.Mobile;

import android.app.*;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import org.xmlpull.v1.XmlPullParserException;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class MainActivity extends Activity {
    private String[] mNDTitles;
    private String[] mNDTitlesDescription;
    private DrawerLayout mDrawerLayout;
    private ListView mNDListView;
    private CharSequence mNDDrawerTitle;
    private CharSequence mNDTitle;
    private ActionBarDrawerToggle mNDToggle;
    private static String file_url = "http://109.172.12.93/media/osticket.xml";
    Fragment fragment = null;
    Bundle args = new Bundle();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mNDTitle = mNDDrawerTitle = getTitle();
        mNDTitles = getResources().getStringArray(R.array.nd_titles);
        mNDTitlesDescription = getResources().getStringArray(R.array.nd_descriptions);

        mDrawerLayout = (DrawerLayout)findViewById(R.id.navigation_drawer_layout);
        mNDListView = (ListView)findViewById(R.id.nd_list_view);
        //mNDListView.setAdapter(new NDListViewAdapter(this,mNDTitles,mNDTitlesDescription));
        NDListViewAdapter adapter = new NDListViewAdapter(this,mNDTitles,mNDTitlesDescription);

        mNDListView.setAdapter(adapter);

        mNDListView.setOnItemClickListener(new DrawerItemClickListener());

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
        mNDToggle = new ActionBarDrawerToggle(
                this,
                mDrawerLayout,
                R.drawable.ic_drawer,
                R.string.drawer_opened,
                R.string.drawer_closed
        ){
            public void onDrawerClosed(View view){
                super.onDrawerClosed(view);
                getActionBar().setTitle(mNDTitle);
                invalidateOptionsMenu();
            }
            public void onDrawerOpened(View drawerView){
                super.onDrawerClosed(drawerView);
                getActionBar().setTitle(mNDTitle);
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mNDToggle);

        if (savedInstanceState == null){
            selectItem(0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mNDListView);
        menu.findItem(R.id.mm_item_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mNDToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch(item.getItemId()) {
            case R.id.mm_item_exit:
                quitFromApplication();
                return true;
            case R.id.mm_item_settings:
                fragmentManager.beginTransaction().replace(R.id.nd_content_frame,new SettingsFragment()).commit();
                break;
            case R.id.mm_item_sync:
                new DownloadXMLFromURL().execute(file_url);
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return super.onOptionsItemSelected(item);
    }

    private void quitFromApplication() {
        AlertDialog.Builder quitDialog = new AlertDialog.Builder(MainActivity.this);
        quitDialog.setTitle(R.string.quit_dialog_title);
        quitDialog.setPositiveButton(R.string.quit_dialog_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
        quitDialog.setNegativeButton(R.string.quit_dialog_no, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        quitDialog.show();
    }

    public void selectItem(int position){
        switch (position){
            case 0:
                fragment = new ViewTicketsFragment();
                args.putInt(ViewTicketsFragment.ARG_ITEM_NUMBER,position);
                fragment.setArguments(args);
                fragmentManager.beginTransaction().replace(R.id.nd_content_frame,fragment).commit();
                mNDListView.setItemChecked(position,true);
                setTitle(mNDTitles[position]);
                mDrawerLayout.closeDrawer(mNDListView);
                break;
            case 1:
                fragment = new FindTicketFragment();
                break;
            case 2:
                fragment = new AddTicketFragment();
                break;
            case 3:
                //
                break;
            default:
                break;
        }
        mDrawerLayout.closeDrawer(mNDListView);
        mNDListView.setItemChecked(position,true);
        setTitle(mNDTitles[position]);
        mDrawerLayout.closeDrawer(mNDListView);
    }

    @Override
    public void setTitle(CharSequence title){
        mNDTitle = title;
        getActionBar().setTitle(mNDTitle);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mNDToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mNDToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(mNDListView)){
            mDrawerLayout.closeDrawer(mNDListView);
        }
    }

    private class DrawerItemClickListener implements android.widget.AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            selectItem(position);
        }
    }

    @Override
    protected void onStart() {
        //TODO Написать вызов загрузки настроек (SharedPreferences)
        super.onStart();
    }

    @Override
    protected void onResume() {
        //TODO Написать вызов загрузки настроек (SharedPreferences)
        super.onResume();
    }

    @Override
    protected void onPause() {
        //TODO Написать вызов сохранения настроек (SharedPreferences)
        super.onPause();
    }

    @Override
    protected void onStop() {
        //TODO Написать вызов сохранения настроек (SharedPreferences)
        super.onStop();
    }

    class DownloadXMLFromURL extends AsyncTask<String, Void, List<Ticket>> {

        @Override
        protected List<Ticket> doInBackground(String... urls) {
            try {
                return loadXmlFromNetwork(urls[0]);
            }
            catch (IOException ioe){
                ioe.printStackTrace();
            }
            catch (XmlPullParserException xppe){
                xppe.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<Ticket> file_url) {
            setContentView(R.layout.main);
            super.onPostExecute(file_url);
        }
    }

    private List<Ticket> loadXmlFromNetwork(String url) throws XmlPullParserException, IOException{
        InputStream inputStream = null;
        StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();
        List<Ticket> ticketList = null;
        try{
            inputStream = downloadUrl(url);
            ticketList = stackOverflowXmlParser.parse(inputStream);
            return ticketList;
        }
        finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    private InputStream downloadUrl(String url) throws IOException{
        URL fileUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
        connection.setReadTimeout(10000);
        connection.setConnectTimeout(15000);
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        return inputStream;
    }

}
